import loginHelper from '@/pluginHelper/login'
import { getDownloadablePrograms, installableContentInfo } from '@/api/appliance'
import { getArticleDetail } from '@/api/content'
import aesHelper from '@/utils/aesHelper'
import { reportEventData } from '@/dataReport/dataReportUtil'
import keyUtils from '@/dataReport/keyUtils'
import { jumpMP, getPageQuery } from '../utils/mpHelper'
import { orderPermanentInfo } from '@/utils/deviceMessageSubscribe/deviceMessage'
import { showLoading, toPage } from '@/utils/mpHelper'
import netconfig from '@/config/netconfig'
import { reConnect } from '@/utils/waitforpairing'

import { useLoadStore, type State } from '@/store/loading'
import { useApplianceStore } from '@/store/appliance'
import { useAuthStore } from '@/store/auth'

import type { ApplianceData } from '@/types/appliance'
import $$Rangers from '@datarangers/sdk-mp'
import { TrackType, trackEvent } from '@/dataReport/tracks'
import { decryptPhone } from '@/api/account'
import { getBannerInfo, jumpBannerWeb } from '@/api/common'
import i18n from '@/i18n'
// 特殊处理的场景值，CsPilot2020为扫码时需要跳转到首页
const specialScenes = ['CsPilot2020']
const applianceStore = useApplianceStore()
const loadStore = useLoadStore()
const authStore = useAuthStore()

type LoadOptions = {
  landing_type?: string
  miniprogram_id?: string
  appid?: string
  landingPage?: string
  article_id?: string
  recipe_id?: number
  isDefault?: string
  haid?: string
  program_key?: string
  sceneName?: string
  brand?: string
  appliance_type?: string
  vib?: string
  scenario?: number | string
  applianceVib?: string | undefined
  haId?: string
  onLogin?: string
  utm_source?: string
  utm_medium?: string
  scene?: number
  phoneData?: string
  sign?: string
  web_type?: string
}

let urlOptions: LoadOptions
let nav = false
let isComfirmSwitchUserPhoneNumber: boolean = true //用户是否点击切换手机号

/**
 * 处理loding落地页的options
 * redirectToPage：直接跳转、      openXX：配置后跳转
 * 0：跳转其他小程序(官方商城)
 * 1：跳转指定路径
 * 2：跳转指定路径指定场景
 * 3：打开文章详情
 * 4：打开菜谱详情
 * 5：打开指定家电类型详情页
 * 6：打开菜谱详情
 * 7：打开指定家电类型详情页里指定页面
 * 8：打开指定家电类型的某个家电的某个详情页
 * 9: 跳转到首页并展示引导配对弹框
 * 10:节日温度
 * 11:跳转其它小程序（非商城
 * 12:跳转到cookit(0731新增)
 * 13:跳转到banner问卷页
 */
function choosePath(options: LoadOptions) {
  let url = ''
  let utm_source = options.utm_source ? options.utm_source : 'hc'
  // 配置utm_source
  $$Rangers.config({
    utm_source: utm_source,
  })

  trackEvent('loading_page_jump', options, TrackType.BusinesssScene)

  if (typeof options.landing_type === 'number') {
    options.landing_type = options.landing_type as string
  }
  if (!options.landing_type || options.landing_type === 'undefined' || options.landing_type === 'null') {
    redirectToPage()
    return false
  }
  urlOptions = options // 赋值给全局
  switch (options.landing_type) {
    case '0':
      if (options.miniprogram_id || options.appid) {
        loadStore.toOtherMiniprogram = true // 打开 "跳转到其他小程序" 提示弹窗
      } else {
        loadStore.errorHint = true
        loadStore.errorTxt = 'appid缺失'
      }
      break
    case '1':
      let landingPage = options.landingPage
      let web_type = options.web_type
      if (web_type) {
        // 适配问卷星跳转
        landingPage = landingPage + `?web_type=${web_type}`
      }
      redirectToPage(landingPage)

      break
    case '2':
      openParamsPages(options) // 筛选scenario参数
      break
    case '3':
      openArticle(options.article_id || '') // 打开文章详情页
      break
    case '4':
      url = `/pages/discovery/recipeDetail/recipeDetail?recipeId=${options.recipe_id}`
      if (Number(options.isDefault) == 1) {
        url = `/pages/discovery/recipeDetail_1/recipeDetail?recipeId=${options.recipe_id}`
      } else if (Number(options.isDefault) == 2) {
        url = `/pages/discovery/oemRecipeDetail/oemRecipeDetail?recipeId=${options.recipe_id}`
      }
      redirectToPage(url)
      break
    case '5':
      isLogin(
        () => {
          openAppliances(options, false)
        },
        options,
        options.landing_type
      )
      break
    case '6':
      url = `/pages/discovery/recipeDetail/recipeDetail?recipeId=${options.recipe_id}`
      if (Number(options.isDefault) == 1) {
        url = `/pages/discovery/recipeDetail_1/recipeDetail?recipeId=${options.recipe_id}`
      } else if (Number(options.isDefault) == 2) {
        url = `/pages/discovery/oemRecipeDetail/oemRecipeDetail?recipeId=${options.recipe_id}`
      }
      navigateToPage(url)
      break
    case '7':
      isLogin(
        () => {
          openAppliances(options, options.haid ? true : false)
        },
        options,
        options.landing_type
      )
      break
    case '8':
      isLogin(
        () => {
          openAppliances(options, options.haid ? true : false, options.program_key)
        },
        options,
        options.landing_type
      )
      break
    case '9':
      //客服消息跳转:HCCN-4625
      redirectToPage(options.landingPage)
      break
    case '10':
      isLogin(
        () => {
          openAppliances(options, false, '', true)
        },
        options,
        options.landing_type
      )
      break
    case '11':
      if (options.sceneName == 'deviceCard') {
        reportEventData(keyUtils.KEY_DEVICE_CARD, {
          haid: options.haid,
          brand: options.brand,
          producttype: options.appliance_type,
          productvib: options.vib,
        })
      }
      if (options.miniprogram_id)
        jumpMP(
          options.miniprogram_id,
          decodeURIComponent(options.landingPage || ''),
          {},
          'Navigator.Loading.LandingType.11'
        )
      break
    case '13':
      getBannerInfo().then((res) => {
        let bannerurl = ''
        let actionType = '0'
        let appid: string | null = null
        if (res.code === 0 && res.data && res.data.length > 0) {
          actionType = res.data[0].actionType
          bannerurl = res.data[0].landingPage
          appid = res.data[0].appid
          let questionnaireUrl = ''
          let myUrl = ''
          if (actionType === '1' || actionType === '3') {
            questionnaireUrl = `/pages/webview/webview?url=${bannerurl}`
            myUrl = `pages/webview/webview?url=${bannerurl}`
            jumpBannerWeb(questionnaireUrl, myUrl, actionType, appid as string)
          } else {
            questionnaireUrl = '/' + bannerurl
            myUrl = `pages/navigator/index`
            loadStore.appId = appid as string
            loadStore.bannerurl = bannerurl
            loadStore.toOtherMiniprogram = true
            loadStore.customText = i18n.global.t('Navigator.loading.My.Dialog.text')
            loadStore.okText = i18n.global.t('Navigator.loading.My.Confirm.text')
          }
          uni.removeStorageSync('bannerClose')
        } else {
          toPage(`/pages/navigator/index/index`)
        }
      })
      break
    default:
      redirectToPage(options.landingPage)
      break
  }
}

// 打开本小程序指定场景
function openParamsPages(options: LoadOptions) {
  if (typeof options.scenario === 'number') {
    options.scenario = options.scenario.toString()
  }
  let url = ''
  /**
   * 0 跳转到首页，并打开虚拟体验
   * 1 跳转到首页，拉起去配对dialog
   *
   * 保留位
   *
   */
  switch (options.scenario) {
    case '0':
      url = '/pages/navigator/index/index?showVideo=1'
      break
    case '1':
      url = '/pages/navigator/index/index?cur=0&applianceVib=' + options.applianceVib
      break
    default:
      url = options.landingPage || ''
      break
  }
  redirectToPage(url)
}

// 打开文章页
async function openArticle(id: string) {
  let res = await getArticleDetail(id)
  if (res.code == 0) {
    uni.navigateTo({
      url:
        '/pages/webview/webview?url=' +
        encodeURIComponent(res.data.htmlCode) +
        '&title=' +
        encodeURIComponent(res.data.title) +
        '&img=' +
        encodeURIComponent(netconfig.ASSETSPRE + res.data.pic),
    })
  } else {
    // control.errorHandle(res, that, 'discovery.js/gotoDetail()');
    redirectToPage() // 返回首页
  }

  // 如果登录了就上报数据
  if (!authStore.isLogin) {
    return false
  }
  let articleCatalogTemp
  switch (res.data.bannerId) {
    case 1:
      articleCatalogTemp = '贴士'
      break
    case 2:
      articleCatalogTemp = '科普'
      break
    case 3:
      articleCatalogTemp = '食材'
      break
    default:
      break
  }
}

// 查找设备
async function openAppliances(
  options: LoadOptions,
  isHaid?: boolean,
  needShowProgram = '',
  flexHoliday?: boolean | undefined
) {
  if (options.sceneName == 'Siemens_ProgramDownload_btn') {
    reportEventData(keyUtils.KEY_BUTTON_CLICK, {
      page_name: 'loading页',
      des: '从西门子小程序跳转过来',
    })
  } else if (options.sceneName == 'deviceCard') {
    reportEventData(keyUtils.KEY_DEVICE_CARD, {
      haid: options.haid,
      brand: options.brand,
      producttype: options.appliance_type,
      productvib: options.vib,
    })
  }
  await applianceStore.loadList(true)
  if (!applianceStore.current) {
    //OMP未配对家电过来的去确认家电页
    if (isComfirmSwitchUserPhoneNumber && options.vib && !options.haid && options.utm_source?.includes('fusion')) {
      const vib = options.vib
      const pairingSource = options.utm_source
      const pairingPath = `/pages/pairing/confirmAppliance/index?vib=${vib}&pairingSource=${pairingSource}`
      toPage(pairingPath)
    } else {
      redirectToPage() // 前往首页
    }
    return
  } else {
    //OMP未配对家电过来的去确认家电页
    if (isComfirmSwitchUserPhoneNumber && options.vib && !options.haid && options.utm_source?.includes('fusion')) {
      const vib = options.vib
      const pairingSource = options.utm_source
      const pairingPath = `/pages/pairing/confirmAppliance/index?vib=${vib}&pairingSource=${pairingSource}`
      toPage(pairingPath)
      return
    }
  }
  applianceStore.setCurrentType(options.appliance_type || '')
  let typeArr = applianceStore.currentType

  if (flexHoliday) {
    let vibStr = decodeURIComponent(options.vib || '').replace(/\[|]/g, '')
    let vibs = vibStr.split(',')
    typeArr = typeArr.filter((item) => {
      let sameVib = false
      for (let i = 0; i < vibs.length; i++) {
        if (item.vib == vibs[i]) {
          sameVib = true
          break
        }
      }
      return sameVib
    })
  }
  let currentHA: ApplianceData | { type: string; haId: string; vib: string }
  currentHA = {
    type: '',
    haId: '',
    vib: '',
  }
  let hasType =
    typeArr.some((item) => {
      if (isHaid && options.haid == item.haId) {
        currentHA = item
        return true
      }
    }) ||
    typeArr.some((item) => {
      if (!isHaid) {
        currentHA = item
        return true
      }
    })
  let hasTypeConnected =
    typeArr.some((item) => {
      if (isHaid && item.connected && options.haid == item.haId) {
        currentHA = item
        return true
      }
    }) ||
    typeArr.some((item) => {
      if (!isHaid && item.connected) {
        currentHA = item
        return true
      }
    })

  if (!hasType) {
    if (options.sceneName == 'deviceCard') {
      uni.showModal({
        title: '提示',
        content: '您访问的家电不存在，请重新配对',
        showCancel: true,
        cancelText: '我知道了',
        confirmText: '去配对',
        confirmColor: '#4475D5',
        success(res) {
          if (res.confirm) {
            reConnect(options.vib, '设备卡片家电不存在重连')
          } else if (res.cancel) {
            redirectToPage() // 返回主页
          }
        },
      })
      return
    } else if (options.sceneName == 'Siemens_ProgramDownload_btn') {
      uni.showModal({
        title: '提示',
        content: '暂无支持该程序的洗碗机',
        showCancel: false,
        success() {
          redirectToPage() // 返回主页
        },
      })
      return
    }
  }
  if (!hasTypeConnected) {
    let errorTxt = ''
    if (isHaid) {
      let errName = ''
      typeArr.some((item) => {
        if (options.haid == item.haId) {
          errName = item.name
          return true
        }
      })
      errorTxt = errName
        ? errName + `已离线，请检查：\n1.设备是否已通电并开机；\n2.设备连接的路由器是否正常工作，网络通畅`
        : `设备列表中未发现该设备，请手动重连该设备`
    } else {
      errorTxt = `发现${typeArr.length}台设备，均离线，请检查：\n1.设备是否已通电并开机；\n2.设备连接的路由器是否正常工作，网络通畅`
    }

    loadStore.errorHint = true
    loadStore.errorTxt = errorTxt
    return
  }

  let pageUrl = '/pages/appliance/'

  if (options.sceneName == 'Siemens_ProgramDownload_btn') {
    // 只有这处的haId的‘i'是大写，后续考虑修改成统一小写
    if (options.haId) {
      let resList = await getDownloadablePrograms(options.haId)
      if (resList.code == 0) {
        let programs = resList.data
        for (let j = 0; j < programs.length; j++) {
          if (programs[j].featureKey == 'Dishcare.Dishwasher.Program.BabyCare') {
            uni.navigateTo({
              url:
                pageUrl +
                options.appliance_type +
                '/programDownload/programDownload?' +
                'haId=' +
                options.haId +
                '&sceneName=Siemens_ProgramDownload_btn&program_key=' +
                programs[j].featureKey +
                '&name=' +
                programs[j].name +
                '&title=' +
                programs[j].title +
                '&sourceId=' +
                programs[j].sourceId,
            })
            return
          }
        }
      } else {
        // control.errorHandle(resList, this, 'loading.js/openAppliances()');
      }
    } else {
      let isBabyCare = false
      let isExitDownloadAppliance = false
      let isSiemensDishwasher = false
      for (let i = 0; i < typeArr.length; i++) {
        if (typeArr[i].brand == 'Siemens') {
          isSiemensDishwasher = true
          let res = await installableContentInfo(typeArr[i].haId)
          if (res.code == 0) {
            let isShowDownload = res.data
            if (isShowDownload) {
              isExitDownloadAppliance = true
              let resList = await getDownloadablePrograms(typeArr[i].haId)
              if (resList.code == 0) {
                let programs = resList.data
                for (let j = 0; j < programs.length; j++) {
                  if (programs[j].featureKey == 'Dishcare.Dishwasher.Program.BabyCare') {
                    isBabyCare = true
                    uni.navigateTo({
                      url:
                        pageUrl +
                        typeArr[i].type +
                        '/programDownload/programDownload?' +
                        'haId=' +
                        typeArr[i].haId +
                        '&sceneName=Siemens_ProgramDownload_btn&program_key=' +
                        programs[j].featureKey +
                        '&name=' +
                        programs[j].name +
                        '&title=' +
                        programs[j].title +
                        '&sourceId=' +
                        programs[j].sourceId,
                    })
                    break
                  }
                }
              } else {
                // control.errorHandle(resList, this, 'loading.js/openAppliances()');
              }
            }
          } else {
            // control.errorHandle(res, this, 'loading.js/openAppliances()');
          }
        }
      }
      if (!isBabyCare || !isExitDownloadAppliance || !isSiemensDishwasher) {
        uni.showModal({
          title: '提示',
          content: '暂无支持该程序的洗碗机',
          showCancel: false,
          success() {
            redirectToPage() // 返回主页
          },
        })
      }
    }
    return
  }
  // 兼容冰箱相关的品类页面路径
  let typePath = currentHA.type + '/' + currentHA.type
  if (['Freezer', 'Refrigerator'].includes(currentHA.type)) {
    typePath = 'FridgeFreezer/FridgeFreezer'
  }
  showLoading(async () => {
    try {
      await orderPermanentInfo(currentHA.haId)
    } finally {
      nav = false
      applianceStore.setCurrent(currentHA.haId)
      await toPage(`${pageUrl}${typePath}`, {
        ...options,
        haId: currentHA.haId,
        vib: currentHA.vib,
        type: currentHA.type,
        needShowProgram,
        utm_source: options.utm_source,
      })
    }
  })
}

// 跳转页面
function redirectToPage(url = '') {
  url = url && url.indexOf('pages') !== -1 ? url : '/pages/navigator/index/index'
  url = url.charAt(0) === '/' ? url : '/' + url
  // 拼接haId
  const pageQuery = getPageQuery()
  if (pageQuery.haid && !url.includes('haid')) {
    const queryAppendMark = url.includes('?') ? '&' : '?'
    url = url.concat(`${queryAppendMark}haid=${pageQuery.haid}`)
  }
  uni.redirectTo({
    url,
    fail: () => {
      uni.redirectTo({
        url: '/pages/navigator/index/index',
      })
    },
  })
}
// 跳转页面
function navigateToPage(url = '') {
  url = url && url.indexOf('pages') !== -1 ? url : '/pages/navigator/index/index'
  url = url.charAt(0) === '/' ? url : '/' + url
  // 拼接haId
  const pageQuery = getPageQuery()
  if (pageQuery.haid && !url.includes('haid')) {
    const queryAppendMark = url.includes('?') ? '&' : '?'
    url = url.concat(`${queryAppendMark}haid=${pageQuery.haid}`)
  }

  uni.navigateTo({
    url,
    fail: () => {
      uni.redirectTo({
        url: '/pages/navigator/index/index',
      })
    },
  })
}

// 检查是否已登录
async function isLogin(callback: any, options: any, landingType: string) {
  //处理多小程序跳转的不同账号传递的逻辑
  if (options.phoneData && options.sign) {
    let res = await decryptPhone(options.sign, options.phoneData)
    let oldAccoutNumber = aesHelper.decrypt(wx.getStorageSync('ciamId'), authStore.key, authStore.iv)
    if (res.code == 0 && res.data) {
      const accoutNumber = res.data.replace(/^(\+{0,1}86){0,1}/, '')
      if (oldAccoutNumber) {
        if (accoutNumber != oldAccoutNumber) {
          uni.showModal({
            title: '提示',
            content: `您当前已使用账号${oldAccoutNumber}登录，是否确认切换为账号${accoutNumber}登录？`,
            showCancel: true,
            cancelText: '取消',
            confirmText: '确认',
            confirmColor: '#4475D5',
            success(res) {
              if (res.confirm) {
                authStore.removeAllUserInfo()
                uni.setStorageSync('ciamId', aesHelper.encrypt(accoutNumber, authStore.key, authStore.iv))
                authStore.accessPhoneNumber = accoutNumber
                handleSwitchPhoneNumber(landingType)
                isComfirmSwitchUserPhoneNumber = true
              } else if (res.cancel) {
                handleSwitchPhoneNumber(landingType)
                isComfirmSwitchUserPhoneNumber = false
              }
            },
          })
        } else {
          //使用老账号自动刷新token
          callback()
        }
      } else {
        //使用新账号自动刷新token
        wx.setStorageSync('ciamId', aesHelper.encrypt(accoutNumber, authStore.key, authStore.iv))
        callback()
      }
    } else {
      callback()
    }
  } else {
    if (authStore.isLogin) {
      callback()
      return false
    }
    if (urlOptions.onLogin === 'true') {
      redirectToPage() // 前往首页
    } else {
      goLoginPage() // 前往登录页
    }
  }
}

// 前往登录页
function goLoginPage() {
  let obj = {
    path: 'pages/navigator/loading/loading',
    query: urlOptions,
  }
  loginHelper.noCiamIdLogin('reLaunch', obj)
}

/**
 * 对于启动时特殊的场景值页面跳转
 * @param options
 */
export function specialSceneJumpOnLaunch(options: any) {
  let queryObj = options.query
  if (queryObj) {
    let scene = queryObj.scene
    if (specialScenes.indexOf(scene) !== -1) {
      // 这里把特殊的scene 记录成utm_source
      $$Rangers.config({
        utm_source: scene ? scene : 'hc',
      })
      trackEvent('loading_page_special_jump', options, TrackType.BusinesssScene)
      uni.redirectTo({
        url: '/pages/navigator/index/index',
      })
      return true
    }
  }
  return false
}

function handleSwitchPhoneNumber(landingType: string) {
  switch (landingType) {
    case '5':
      openAppliances(urlOptions, false)
      break
    case '7':
      openAppliances(urlOptions, urlOptions.haid ? true : false)
      break
    case '8':
      openAppliances(urlOptions, urlOptions.haid ? true : false, urlOptions.program_key)
      break
    case '10':
      openAppliances(urlOptions, false, '', true)
      break
  }
}

export { choosePath, openArticle }
